package com.ctrip.corp.obt.shard.context;

import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;

import java.util.List;
import java.util.Optional;

public class PermissionContext {

    private static final String ORG_IDS = "orgIds";

    private static final String CORP_IDS = "corpIds";

    public static void setOrgIds(String orgIds) {
        Optional.ofNullable(orgIds).ifPresent(value -> addContextParams(ORG_IDS, orgIds));
    }

    public static void setOrgIds(List<String> orgIds) {
        if (CollectionUtils.isEmpty(orgIds)) {
            return;
        }
        addContextParams(ORG_IDS, StringUtils.join(orgIds, ","));
    }

    public static String getOrgIds() {
        return (String) getContextParams(ORG_IDS);
    }

    public static void setCorpIds(String corpIds) {
        Optional.ofNullable(corpIds).ifPresent(value -> addContextParams(CORP_IDS, corpIds));
    }

    public static void setCorpIds(List<String> corpIds) {
        if (CollectionUtils.isEmpty(corpIds)) {
            return;
        }
        addContextParams(CORP_IDS, StringUtils.join(corpIds, ","));
    }

    public static String getCorpIds() {
        return (String) getContextParams(CORP_IDS);
    }

    private PermissionContext() {}

    private static Object getContextParams(String contextParamKey) {
        return RequestContext.getCurrentContext().getContextParams(contextParamKey);
    }

    private static void addContextParams(String contextParamKey, Object contextParamValue) {
        RequestContext.getCurrentContext().addContextParams(contextParamKey, contextParamValue);
    }

}
